package com.app.couponsharelife.ui.main.login

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.databinding.FragmentRegisterBinding
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.FinishActivityManager
import com.app.couponsharelife.ui.main.MainActivity
import com.app.couponsharelife.ui.viewmodel.LoginViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_register.*
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.collections.HashMap

/**
 * Created by guluwa on 2018/11/21.
 */
class RegisterFragment : LazyFragment() {

    override val viewLayoutId: Int get() = R.layout.fragment_register

    private var disposable: Disposable? = null

    private var countDownNum: Int = 0

    private var mViewModel: LoginViewModel? = null

    private var isAllEdit = false

    private var isUserKnow = false

    companion object {
        fun newInstance(): RegisterFragment {
            val fragment = RegisterFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }

    override fun initViews() {
        initEditText()
        initClickEvent()
    }

    private fun initEditText() {
        watchEditText(etInviteCode, ivDeleteInviteCode)
        watchEditText(etPhoneNum, ivDeletePhoneNum)
        watchEditText(etCheckCode, null)
        watchEditText(etPassword, null)
    }

    private fun initClickEvent() {
        (mViewDataBinding as FragmentRegisterBinding).listener = View.OnClickListener {
            when (it.id) {
                R.id.ivDeleteInviteCode -> etInviteCode.setText("")
                R.id.ivDeletePhoneNum -> etPhoneNum.setText("")
                R.id.tvSendCheckCode -> {
                    sendCheckCode()
                }
                R.id.ivPassWordVisible -> {
                    changePassWordVisible()
                }
                R.id.tvRegisterBtn -> {
                    userRegister()
                }
                R.id.mReadUserKnowView -> {
                    isUserKnow = !isUserKnow
                    if (isUserKnow) ivReadUserKnow.setImageResource(R.drawable.ic_register_know)
                    else ivReadUserKnow.setImageResource(R.drawable.ic_register_no_know)
                }
                R.id.tvReadUserKnow -> {
                    startActivity(Intent(context, UserKnowActivity::class.java))
                }
            }
        }
    }

    private fun sendCheckCode() {
        if (TextUtils.isEmpty(etPhoneNum.text)) {
            showToastMsg("请输入手机号")
            return
        }
        if (etPhoneNum.text.toString().length<11) {
            showToastMsg("请输入正确的手机号")
            return
        }
        if (AppUtils.isMobile(etPhoneNum.text)) {
            showToastMsg("请输入正确的手机号")
            return
        }
        val map = HashMap<String, String>()
        map["mobile"] = etPhoneNum.text.toString().trim()
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel?.freshUserRegisterCheckCode(map, true)
    }

    private fun userRegister() {
        if (!isUserKnow) {
            showToastMsg("请先阅读用户协议")
            return
        }
        if (TextUtils.isEmpty(etInviteCode.text)) {
            showToastMsg("请输入邀请码")
            return
        }
        if (TextUtils.isEmpty(etPhoneNum.text)) {
            showToastMsg("请输入手机号")
            return
        }
        if (TextUtils.isEmpty(etCheckCode.text)) {
            showToastMsg("请输入验证码")
            return
        }
        if (TextUtils.isEmpty(etPassword.text)) {
            showToastMsg("请输入密码")
            return
        }
        val map = HashMap<String, String>()
        map["requestcode"] = etInviteCode.text.toString().trim()
        map["mobile"] = etPhoneNum.text.toString().trim()
        map["code"] = etCheckCode.text.toString().trim()
        map["pwd"] = etPassword.text.toString().trim()
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel?.freshUserRegister(map, true)
    }

    private fun changePassWordVisible() {
        if (etPassword.transformationMethod === HideReturnsTransformationMethod.getInstance()) {
            //显示密文
            etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
            Glide.with(context!!).asBitmap().load(R.drawable.ic_edit_text_close_eye).into(ivPassWordVisible)
        } else {
            //显示明文
            etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
            Glide.with(context!!).asBitmap().load(R.drawable.ic_edit_text_open_eye).into(ivPassWordVisible)
        }
        //保证每次切换明文密文后光标都在最后面，默认是会切换到最前端
        etPassword.setSelection(etPassword.text.length)
    }

    override fun lazyLoad() {

    }

    private fun watchEditText(editText: EditText, imageView: ImageView?) {
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (TextUtils.isEmpty(s)) {
                    imageView?.visibility = View.INVISIBLE
                    imageView?.isClickable = false
                } else {
                    imageView?.visibility = View.VISIBLE
                    imageView?.isClickable = true
                }
                if (!TextUtils.isEmpty(etInviteCode.text) &&
                        !TextUtils.isEmpty(etPhoneNum.text) &&
                        !TextUtils.isEmpty(etCheckCode.text) &&
                        !TextUtils.isEmpty(etPassword.text)) {
                    tvRegisterBtn.setBackgroundResource(R.drawable.ic_act_login_btn_active)
                } else {
                    tvRegisterBtn.setBackgroundResource(R.drawable.shape_red_ff0_ff4)
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    private fun sendCheckCodeSuccess() {
        countDownNum = 59
        tvCheckCodeNum.visibility = View.VISIBLE
        tvSendCheckCode.visibility = View.INVISIBLE
        tvSendCheckCode.isClickable = false
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)//10s 倒计时
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ aLong ->
                    if (countDownNum < 0)
                        goAhead()
                    else {
                        tvCheckCodeNum.text = "${countDownNum}s后重发"
                        countDownNum--
                    }
                }) { goAhead() }
    }

    private fun goAhead() {
        tvCheckCodeNum.visibility = View.INVISIBLE
        tvSendCheckCode.visibility = View.VISIBLE
        tvSendCheckCode.isClickable = true
        disposable?.dispose()
        disposable == null
    }

    override fun onDestroy() {
        if (disposable != null && !disposable!!.isDisposed) {
            disposable?.dispose()
            disposable == null
        }
        super.onDestroy()
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(LoginViewModel::class.java)
        if (!mViewModel!!.userRegisterCheckCode()!!.hasObservers()) {
            mViewModel!!.userRegisterCheckCode()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserRegisterCheckCode(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserRegisterCheckCode(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserRegisterCheckCode(hashMapOf(), false)
                        if (it.data!!.code == 1 && it.data.data != null) {
                            sendCheckCodeSuccess()
                        } else {
                            showToastMsg("请求失败")
                        }
                    }
                }
            })
            mViewModel!!.userRegister()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserRegister(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserRegister(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshUserRegister(hashMapOf(), false)
                        if (it.data!!.code == 1 && it.data.data != null) {
                            AppUtils.setString(Contacts.TOKEN, it.data.data!!.token)
                            AppUtils.setString(Contacts.USERID, it.data.data!!.id)
                            AppUtils.setString(Contacts.USERTYPE, it.data.data!!.type)
                            AppUtils.setString(Contacts.ADZONE_ID, it.data.data!!.adzoneid)
                            registerInform()
                        } else {
                            dismissProgressDialog()
                            showToastMsg("请求失败")
                        }
                    }
                }
            })
            mViewModel!!.registerInform()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshRegisterInform(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshRegisterInform(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshRegisterInform(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            showToastMsg("注册成功")
                            FinishActivityManager.getInstance().finishAllActivity()
                            startActivity(Intent(context, MainActivity::class.java))
                        } else {
                            showToastMsg("请求失败")
                        }
                    }
                }
            })
        }
    }

    private fun registerInform() {
        val map = HashMap<String, String>()
        map["mobile"] = etPhoneNum.text.toString().trim()
        mViewModel?.freshRegisterInform(map, true)
    }
}